package com.haocang.szgm.ui.msg.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.haocang.commonlib.network.interfaces.InitDataBeanBack;
import com.haocang.commonlib.network.interfaces.InitDataCallBack;
import com.haocang.szgm.R;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.szgm.ui.analysis.activity.DataAnalysisActivity;
import com.haocang.szgm.ui.home.interfaces.SendMsaFromFragment;
import com.haocang.szgm.ui.msg.activity.MsgDetailActivity;
import com.haocang.szgm.ui.msg.adapter.AlarmListAdapter;
import com.haocang.szgm.ui.msg.bean.AlarmBean;
import com.haocang.szgm.ui.msg.bean.MsgBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.szgm.utils.config.WebApi;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * 创建时间：2018/12/21
 * 编 写 人：ShenC
 * 功能描述：消息界面
 */
public class AlarmFragment extends Fragment {
    private View view;
    private Context context;
    private TextView tv_name;
    private SwipeMenuRecyclerView recyclerview;
    private RefreshLayout refreshLayout;
    private AlarmListAdapter mAlarmListAdapter;
    private SendMsaFromFragment sendMessage;
    private LinearLayout lin_more;
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        sendMessage = (SendMsaFromFragment) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_alarm, container, false);
        context = this.getActivity();

        initView();

        initEvent();

        refreshLayout.autoRefresh();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData(null);
    }

    private void initView() {

        tv_name = view.findViewById(R.id.tv_name);
        tv_name.setText("数据报警");

        recyclerview = view.findViewById(R.id.recyclerview);
        refreshLayout = view.findViewById(R.id.refreshLayout);
        lin_more = view.findViewById(R.id.lin_more);
        lin_more.setVisibility(View.INVISIBLE);
    }

    private void initEvent() {

        mAlarmListAdapter = new AlarmListAdapter(context);
        recyclerview.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL) {
            @Override
            public boolean canScrollVertically() {
                return true;//是否允许滑动
            }
        });

        recyclerview.setSwipeItemClickListener(new SwipeItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                AlarmBean bean = mAlarmListAdapter.getItem(position);
                ToastShow(bean.getAlarmName());
            }
        });



        //设置侧滑菜单
        recyclerview.setSwipeMenuCreator(new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {


                SwipeMenuItem Item = new SwipeMenuItem(context)
                        .setBackground(R.color.grey)
                        .setText("解除报警")
                        .setTextColor(Color.WHITE)
                        .setTextSize(14)
                        // .setImage(R.drawable.icon_delete_02)
                        .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)//设置高，这里使用match_parent，就是与item的高相同
                        .setWidth(250);//设置宽

                SwipeMenuItem mpointItem = new SwipeMenuItem(context)
                        .setBackground(R.color.orange)
                        .setText("查看曲线")
                        .setTextColor(Color.WHITE)
                        .setTextSize(14)
                        // .setImage(R.drawable.icon_delete_02)
                        .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)//设置高，这里使用match_parent，就是与item的高相同
                        .setWidth(200);//设置宽

                swipeRightMenu.addMenuItem(Item);//设置右边的侧滑
                swipeRightMenu.addMenuItem(mpointItem);//设置右边的侧滑
            }
        });


        //设置侧滑菜单的点击事件
        recyclerview.setSwipeMenuItemClickListener(new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                menuBridge.closeMenu();
                //int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。0是左，右是1，暂时没有用到
                int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
                int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
                AlarmBean bean = mAlarmListAdapter.getItem(adapterPosition);
                if(menuPosition == 0){
                    RemoveAram(bean.getAlarmID());
                }else{
                    Intent it = new Intent(context, DataAnalysisActivity.class);
                    it.putExtra("FromHome", false);
                    it.putExtra("HaveDT", true);
                    it.putExtra("DT", bean.getAlarmStartDT());
                    it.putExtra("MPOINT", bean.getMpointID());
                    startActivity(it);
                }
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                sendMessage.RefreshNumber();//主页消息数量刷新
                Config.PAGE_LIMIT = Config.PAGE_SHOW_LIMIT;
                refreshlayout.finishRefresh(20000/*,false*/);//传入false表示刷新失败
                initData(refreshlayout);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadmore(20000/*,false*/);//传入false表示加载失败
                Config.PAGE_LIMIT += Config.PAGE_SHOW_LIMIT;
                initData(refreshlayout);
            }
        });

        recyclerview.setAdapter(mAlarmListAdapter);


    }

    private void initData(final RefreshLayout refreshlayout) {
        String ApiUrl = Config.host + WebApi.Api_AlarmList + "999";

        DataModel.GetApiRequestMode("AlarmBean", ApiUrl, new InitDataBeanBack<AlarmBean>() {
            @Override
            public void callbak(boolean b, List<AlarmBean> list, String msg) {
                if (b) {

                    mAlarmListAdapter.setNewData(list);
                    if (refreshlayout != null) {
                        refreshlayout.finishRefresh(true);//刷新完成
                        refreshlayout.finishLoadmore(true);
                    }
                } else {
                    ToastShow(msg);
                    if (refreshlayout != null) {
                        refreshlayout.finishRefresh(false);
                        refreshlayout.finishLoadmore(false);
                    }
                }
            }
        });
    }



    private void RemoveAram(String id){
        String ApiUrl = Config.host
                + WebApi.Api_RemoveAram + id;
        DataModel.GetApiRequest(context, ApiUrl, new InitDataCallBack() {
            @Override
            public void callbak(boolean b, String string) {

                if(b){
                    try {
                        JSONObject jsonobject = new JSONObject(string);
                        if (jsonobject.getInt("Code") == 0) {
                            initData(null);
                            sendMessage.RefreshNumber();
                        } else {
                            ToastShow(jsonobject.getString("Message"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        ToastShow(e.toString());
                    }

                }else{
                    ToastShow(string);
                }

            }
        });


    }


    //接口回调,接受HomeActivity的指令
    public void RefreshPageData() {
        Log.i(Config.LogFlag, "Msg开始刷新");
        initData(null);
    }

    protected void ToastShow(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

}
